<template>
  <VPage edit :footer="{ offset: 10 }">
    <div class="box">
      <el-card class="box-card box-card1">
        <div class="flex items-center">
          <FormTitle title="基础信息" style="width: 80px" />
          <!-- <span class="mb-[14px] status">{{ formData.plan_status_text }}</span> -->
        </div>

        <XForm ref="formRef" :fieldList="fieldList" :options="formOption" :formData="formData" :originOption="originOption" :rules="rules"> </XForm>
      </el-card>

      <el-card class="box-card my-[8px] box-card2">
        <div>
          <div class="flex">
            <FormTitle title="商品信息" style="margin-bottom: 0px; width: 100px" />
            <div v-if="pageName != 'PurchasePlanStockUpPlanCreate'">
              <VButton type="primary" icon="Plus" @click="openAddGoodsRef">添加商品</VButton>
              <!-- 
              <VButton type="primary" icon="Plus" @click="onUpdate">变 更</VButton> -->
              <VButton type="danger" icon="WarningFilled" @click="onDelete()">删除</VButton>
            </div>
          </div>
          <!-- <div class="my-[14px] flex items-center">
            <el-tabs v-model="activeName" class="tabs" @tab-click="tabHandleClick">
              <el-tab-pane v-for="item in formData.details" :key="item.key" :name="item.reviews_status" :label="`${item.reviews_status_text} (${item.count})`"></el-tab-pane>
            </el-tabs>
            <div class="ml-[16px]">汇总金额： {{ totalAmount }} RMB</div>
          </div> -->
        </div>
        <div class="bbb">
          <vxe-grid v-bind="tableOptins" ref="tableRef" height="auto" />
        </div>
      </el-card>
    </div>

    <template #footer>
      <el-button @click="handleCancel">返回</el-button>
      <el-button type="primary" :disabled="loading" @click="save"> 保存 </el-button>
    </template>
  </VPage>

  <!-- 添加商品弹窗 -->
  <DialogAddGoods ref="DialogAddGoodsRef" @submit="submitAddGoodsRef" :originOption="originOption" />

  <!-- 弹窗 表单编辑 -->
  <ConfirmInput v-model="batchVisible" v-bind="currentConfirm" @submit="handleConfirmSubmit" />

  <!-- ASIN销量趋势 -->
  <AsinSalesTrend ref="AsinSalesTrendRef" />

  <!-- 新增变更单 -->
  <!-- <Details ref="DetailsUpdateRef" /> -->
</template>

<script setup lang="jsx" name="create">
// ASIN销量趋势
import AsinSalesTrend from "@/views/plan/components/AsinSalesTrend/index.vue"
const AsinSalesTrendRef = ref()

// import BaseForm from "./baseForm.vue"

// 新增变更单
// import Details from "@/views/plan/stockUpPlanUpdate/components/details/index.vue"
// const DetailsUpdateRef = ref()
import action from "@/utils/action.js"
// 变更
// const onUpdate = () => {
//   let arr = getSelectRow()
//   if (arr.length != 1) {
//     return ElMessage({ showClose: true, message: "请选择一条数据进行操作", type: "warning" })
//   }
//   if (arr?.[0].review_status != 6) {
//     return ElMessage({ showClose: true, message: "已审核状态才可以变更", type: "warning" })
//   }
//   purchaseDemandSkuDetail({ source_id: arr[0]?.id }).then((res) => {
//     sessionStorage.setItem("PURCHASE_HANDLE", JSON.stringify({ pds_id: res.data.pds_id, demand_no: res.data.demand_no, sku: res.data.sku, sku_no: res.data.sku_no }))
//     action.setGlobalState({
//       changeMicoTabsPath: {
//         path: "/purchase/demand/sku",
//         type: "push",
//       },
//     })
//   })
// }

import {
  stockingPlanCreate,
  stockingPlanDetail,
  stockingPlanTotalAmount,
  planSpaReview,
  planSpaUpdateRemark,
  planSpaDelete,
  planSpaCreate,
  // planSpaUpdateTransportationType,
  // planSpaUpdateShipTime,
  planSpaLog,
  planSpaUpdateStockinQuantity,
  purchaseDemandSkuDetail,
  departmentAmountConfig,
} from "@/api/plan"
const router = useRouter()
const formRef = ref()
const save = async () => {
  // let index = tableOptins.data.findIndex((v) => !v.stocking_quantity || !v.estimated_shipping_time)
  // if (index != -1) {
  //   return ElMessage({ message: `第${index + 1}条数据有数据未填！`, type: "warning" })
  // }
  try {
    await formRef.value.submit()
    if (!tableOptins.data.length) {
      return ElMessage({ message: `请先添加商品！`, type: "warning" })
    }
    let index = -1
    let keysObj = {
      stocking_quantity: "需求数量",
      estimated_shipping_time: "预计发货时间",
      transportation_type: "运输类型",
    }

    for (let i = 0; i < tableOptins.data.length; i++) {
      for (const k in keysObj) {
        if (!tableOptins.data[i][k]) {
          ElMessage({ message: `第${i + 1}条数据 ${keysObj[k]}未填！`, type: "warning" })
          index = i
          break
        }
      }
      if (index != -1) break
    }
    if (index != -1) return
    let plan_spa = tableOptins.data.map((v) => ({
      base_asin_id: v.base_asin_id,
      stocking_quantity: v.stocking_quantity,
      estimated_shipping_time: v.estimated_shipping_time,
      transportation_type: v.transportation_type,
      remark: v.remark,
    }))
    // console.log(plan_spa)
    let params = { ...formData.value, plan_type: 1, plan_spa }
    console.log(params)
    stockingPlanCreate(params).then((res) => {
      // console.log(res)
      ElMessage.success("操作成功")
      handleCancel()
    })
  } catch (error) {}
}

const handleCancel = () => {
  action.setGlobalState({
    changeMicoTabsPath: {
      type: "closeActiveTab",
    },
  })
}

import {
  originOption, // 枚举
  stockUpPlanColumns, // 备货计划明细 列
  handleFunctions, // 操作
  currentConfirmOpt, // 表单编辑 弹窗配置
} from "./config.jsx"
// 操作
const handleFunction = ref({
  // 表格操作
  // 修改需求数量
  // updateQuantity: (row) => {
  //   if ("5,6".includes(row.review_status)) {
  //     ElMessage({ showClose: true, message: "此状态不可修改", type: "warning" })
  //     return
  //   }
  //   planSpaUpdateStockinQuantity({
  //     id: row.id,
  //     stocking_quantity: row?.spa_analysis.stocking_quantity,
  //   }).then((res) => {
  //     queryDtl()
  //     ElMessage.success(res.message)
  //   })
  // },

  // 查看ASIN销量趋势
  openTendencyChart: (row) => {
    AsinSalesTrendRef.value.open(row.base_asin_id)
  },
  // // 修改运输类型
  // updateTransportation: (row) => {
  //   planSpaUpdateTransportationType({
  //     id: row.id,
  //     transportation_type: row.transportation_type,
  //   }).then((res) => {
  //     ElMessage.success(res.message)
  //   })
  // },
  // 修改备注
  editRemark: (row) => {
    openConfirmInput("remark", row)
  },
  // 修改 预计发货时间
  // shipTimeChange: (row) => {
  //   planSpaUpdateShipTime({ id: row.id, estimated_shipping_time: row.estimated_shipping_time }).then((res) => {
  //     ElMessage.success(res.message)
  //   })
  // },
})

onActivated(() => {
  nextTick(() => {}).then(() => {
    // console.log("从新进入")
  })
})

const pageName = ref("")
onMounted(() => {
  pageName.value = router.currentRoute.value.name
  getOption()
  nextTick(() => {
    // 操作
    handleFunctions.value = { ...handleFunctions.value, ...handleFunction.value }
  })
  formData.value.plan_name = `${parseTime(new Date(), "{y}-{m}-{d}")}备货计划`

  // queryDtl()
})

// function getLastDayOfMonth() {
//   const currentDate = new Date()
//   const year = currentDate.getFullYear()
//   const month = currentDate.getMonth() + 1 // 月份从0开始，需要加1
//   const lastDayOfMonth = new Date(year, month, 0).getDate()
//   return lastDayOfMonth
// }

import { enumGet, enumOptions } from "@/api"
import { getAloneEnum } from "@/utils/enumUtils"
// 获取下拉数据
const getOption = async () => {
  const { data } = await enumGet({ name: ["Base.BaseAsinList.IsRequiresStockingEnum", "Base.BaseAsinList.TransportationTypeEnum"] })
  originOption.value["Base.BaseAsinList.IsRequiresStockingEnum"] = data["Base.BaseAsinList.IsRequiresStockingEnum"]
  originOption.value["Base.BaseAsinList.TransportationTypeEnum"] = data["Base.BaseAsinList.TransportationTypeEnum"]
  originOption.value.amazonSite = (await getAloneEnum(["amazonSite"]))?.amazonSite
}
import { parseTime } from "@/utils/ruoyi"
const queryDtl = async () => {
  let { id } = router.currentRoute.value.params
  let res = await stockingPlanDetail({ id })
  res.data.planning_department = Number(res.data.planning_department)
  formData.value = res.data
  console.log(res.data)
  let configParams = {
    department_id: [res.data.planning_department],
    // department_id: [98],
    // update_user_id: res.data.created_by,
    month: parseTime(new Date(), "{y}-{m}"),
    // month: "2024-04",
    // update_time: {
    //   start: "",
    //   end: "",
    //   // start: parseTime(new Date().setDate(1), "{y}-{m}-{d}"),
    //   // end: parseTime(new Date().setDate(getLastDayOfMonth()), "{y}-{m}-{d}"),
    // },
  }
  // console.log(parseTime(new Date().setDate(1), "{y}-{m}-{d}"))
  // console.log(parseTime(new Date().setDate(30), "{y}-{m}-{d}"))
  // const start = new Date();
  // start.setDate(0)
  // start.setDate(1)
  // const end = new Date();
  // console.log(getLastDayOfMonth())
  // console.log(configParams)
  let AmountConfig = (await departmentAmountConfig(configParams))?.data?.[0]
  if (AmountConfig) {
    AmountConfig.employ_amount = AmountConfig.amount - AmountConfig.leave_amount
    formData.value = { ...formData.value, ...AmountConfig }
  }

  // 渲染表格数据
  tabHandleClick()
  nextTick(() => {
    // 计算汇总金额
    stockingPlanTotalAmount({ pr_number: res.data.pr_number }).then((res) => {
      totalAmount.value = res.data.total_amount
    })
  })
}

// import { organizationList, overallOptions } from '@/api/public'
// import { queryList, oplog, getFreeType, setStatus } from './api'
import { ElMessage, ElMessageBox } from "element-plus"
import { onMounted, ref, toRefs } from "vue"
// import {basicSetupAuthList} from '@/Auth/basic-setup.js'

// import Details from "./components/details/index.vue"
import XForm from "@/components/XForm/index.vue"
import FormTitle from "@/components/XForm/FormTitle.vue"
import ConfirmInput from "@/components/ConfirmInput/index.vue"

const tableRef = ref()
const activeName = ref(0)
// 汇总金额
const totalAmount = ref(0)
const tabHandleClick = (tab, event) => {
  nextTick(() => {
    let data = formData.value.details.find((v) => v.reviews_status == activeName.value).list
    tableRef.value.loadData(data)
  })
}

// 添加商品弹窗
import DialogAddGoods from "../components/DialogAddGoods.vue"
const DialogAddGoodsRef = ref()
// 添加商品 弹窗
const openAddGoodsRef = () => {
  DialogAddGoodsRef.value.open()
}
// 添加商品 保存
const submitAddGoodsRef = (value) => {
  // console.log(value)
  // console.log(JSON.stringify(value))
  tableOptins.data = [...tableOptins.data, ...initTableData(value)]
  // let params = {
  //   plan_id: router.currentRoute.value.params.id,
  //   plan_spa: value.map((v) => ({ base_asin_id: v.id, stocking_quantity: 0 })),
  // }
  // planSpaCreate(params).then((res) => {
  //   queryDtl()
  // })
}

const initTableData = (list) => {
  let availabilityKey = [
    ["total_inventory_days", "overseas_warehouse_available_days"],
    ["fba_sellable", "fba_sellable_days"],
    ["fba_in_transit", "fba_in_transit_days"],
    ["overseas_warehouse_in_transit", "overseas_warehouse_in_transit_days"],
    ["overseas_warehouse_available", "overseas_warehouse_available_days"],
  ]
  let tableList = list.map((v) => {
    availabilityKey.forEach(([key, val]) => {
      v.plan_stocking_inventory_availability[key] = v.plan_stocking_inventory_availability?.[val]
    })
    let data = {
      ...v,
      base_asin_id: v.id,
      spa_lt_days: v.plan_lt_days,
      // 库存可售天数
      spa_inventory_availability: v.plan_stocking_inventory_availability,
      // 库存信息
      spa_inventory: v.plan_asin_inventory,
      // 销量信息
      spa_sales: v.asin_sales,
      //  采购信息
      spa_purchases: v.plan_asin_purchases,

      spa_analysis: v.plan_stocking_analysis,
    }
    return data
  })
  return tableList
}

const data = reactive({
  title: "详情",
  formData: {
    plan_type_text: "FBA备货",
  },
  loading: false,

  batchVisible: false,
  currentConfirm: {},
})
const { title, formData, loading, batchVisible, currentConfirm } = toRefs(data)

// 删除
const onDelete = (row = null) => {
  let arr = []
  if (row) {
    arr = [row]
  } else {
    arr = getSelectRow()
    if (!arr.length) {
      return false
    }
  }
  ElMessageBox.confirm(`此操作将删除 ${arr.length}条数据, 是否继续?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "oms-message-confirm-button",
  }).then(async () => {
    try {
      let ids = arr.map((v) => v.id)
      tableOptins.data = tableOptins.data.filter((v) => !ids.includes(v.id))
    } catch (e) {
      throw Error(e)
    }
  })
}

// 开启 弹窗 表单编辑
const openConfirmInput = (type, param) => {
  let confirm = {}
  console.log(param)
  switch (type) {
    case "remark": // 备注
      confirm = currentConfirmOpt.remark
      confirm.form = { rowIndex: param.rowIndex, remark: param.remark }
      break
  }
  confirm.type = type
  currentConfirm.value = confirm
  batchVisible.value = true
}
// 保存 弹窗 表单编辑
const handleConfirmSubmit = async (param) => {
  console.log(param)
  let requests = null
  switch (currentConfirm.value.type) {
    case "remark": // 备注
      // requests = planSpaUpdateRemark
      tableOptins.data[param.rowIndex].remark = param.remark
      break
  }
  // requests(param).then((res) => {
  // ElMessage.success(res.message)
  batchVisible.value = false
  // queryDtl()
  nextTick(() => {
    currentConfirm.value = {}
  })
  // })
}

// 获取已选中的行
const getSelectRow = () => {
  const getCheckboxRecords = tableRef?.value.getCheckboxRecords()
  if (!getCheckboxRecords.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return false
  }
  return getCheckboxRecords
}

const formOption = ref({ inline: true, labelWidth: "180px" })

const publicStyle = { style: { width: "200px" } }
const fieldList = ref([
  { label: "计划名称", field: "plan_name", placeholder: "计划名称", ...publicStyle },
  { label: "PR单", field: "pr_number", disabled: true, placeholder: "PR单", ...publicStyle },
  { label: "备货类型", field: "plan_type_text", disabled: true, placeholder: "备货类型", ...publicStyle },
  // { label: "运营部门", field: "planning_department", disabled: true, placeholder: "运营部门", ...publicStyle },

  // {
  //   field: "planning_department",
  //   type: "cascaderNew",
  //   cascaderType: "department",
  //   placeholder: "运营部门",
  //   itemProps: {
  //     props: {
  //       emitPath: false,
  //       multiple: true,
  //       label: "name",
  //       value: "id",
  //       children: "sub",
  //     },
  //   },
  //   style: { width: "200px" },
  // },
  {
    label: "运营部门",
    field: "planning_department",
    type: "cascaderNew",
    cascaderType: "department",
    placeholder: "运营部门",
    cascaderProps: {
      checkStrictly: true,
      multiple: false,
    },
    ...publicStyle,
  },

  { label: "状态", field: "plan_status_text", disabled: true, placeholder: "状态", ...publicStyle },
  { label: "备注", field: "remarks", ...publicStyle },
  { label: "部门当月采购额度", field: "xxx", disabled: true, placeholder: "部门当月采购额度", ...publicStyle },
  { label: "已使用额度", field: "xxx", disabled: true, placeholder: "已使用额度", ...publicStyle },
  { label: "剩余额度（不包含本单）", field: "xxx", disabled: true, placeholder: "剩余额度（不包含本单）", ...publicStyle },
])
const rules = {
  plan_name: [{ required: true, message: "请输入计划名称", trigger: "blur" }],
  planning_department: [{ required: true, message: "请选择运营部门", trigger: "change" }],
}
// 列表配置
const tableOptins = reactive({
  formConfig: {
    data: {},
  },
  rowConfig: { height: "160" },
  columns: [
    { type: "checkbox", fixed: "left", width: 60 },

    {
      title: "操作",
      width: 100,
      fixed: "right",
      slots: {
        default: ({ row, rowIndex }) => {
          return [
            <div>
              <el-button link type="danger" onClick={() => onDelete(row)}>
                删除
              </el-button>
            </div>,
          ]
        },
      },
    },
  ],
  data: [],
})
tableOptins.columns.unshift(...stockUpPlanColumns)
</script>
<style lang="scss" scoped>
:deep(.tabs) {
  margin-top: 0 !important;
  .el-tabs__header {
    margin-bottom: 0;
  }
}
.box {
  display: flex;
  flex-direction: column;
  height: calc(100% - 50px);
  .box-card1 {
  }
  .box-card2 {
    flex: 1;
    :deep(.el-card__body) {
      display: flex;
      flex-direction: column;
      height: 100%;
      padding-bottom: 10px !important;
      .bbb {
        flex: 1;
        overflow: hidden;
        margin-top: 16px;
      }
    }
  }
}
.status {
  background: #faad14;
  border-radius: 4px 4px 4px 0px;
  color: #fff;
  font-size: 12px;
  padding: 1px 3px;
}
</style>
